package com.example.myapplication

import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import io.flutter.embedding.android.FlutterFragment
import io.flutter.plugin.common.MethodChannel

class MainActivity : AppCompatActivity() {
    private val flutterEngine by lazy {
        (application as MyApplication).flutterEngine
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<Button>(R.id.launch_flutter_button).setOnClickListener {
            launchFlutterScreen()
        }

        findViewById<Button>(R.id.send_data_button).setOnClickListener {
            sendDataToFlutter()
        }
    }

    private fun launchFlutterScreen() {
        val flutterFragment = FlutterFragment.withCachedEngine("my_engine_id")
            .build<FlutterFragment>()

        supportFragmentManager.beginTransaction()
            .replace(R.id.container, flutterFragment)
            .commit()
    }

    private fun sendDataToFlutter() {
        MethodChannel(
            flutterEngine.dartExecutor.binaryMessenger,
            "samples.flutter.dev/battery"
        ).invokeMethod("updateUI", "主动发送的数据")
    }
}